package com.accelstack.cmp.service;

import com.accelstack.cmp.entity.User;
import com.accelstack.cmp.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 用户Service
 */
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    @Transactional
    public User create(User user) {
        // 生成AK/SK
        user.setAccessKey(generateAccessKey());
        user.setSecretKey(passwordEncoder.encode(generateSecretKey()));
        user.setCreatedAt(new Date());
        return userRepository.save(user);
    }
    
    @Transactional
    public User update(User user) {
        user.setUpdatedAt(new Date());
        return userRepository.save(user);
    }
    
    @Transactional
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }
    
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }
    
    public Optional<User> findByAccessKey(String accessKey) {
        return userRepository.findByAccessKey(accessKey);
    }
    
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    public List<User> findAll() {
        return userRepository.findAll();
    }
    
    public Page<User> findAll(Pageable pageable) {
        return userRepository.findAll(pageable);
    }
    
    /**
     * 验证AK/SK
     */
    public boolean validateCredentials(String accessKey, String secretKey) {
        Optional<User> userOpt = userRepository.findByAccessKey(accessKey);
        if (userOpt.isEmpty()) {
            return false;
        }
        User user = userOpt.get();
        return passwordEncoder.matches(secretKey, user.getSecretKey());
    }
    
    /**
     * 更新最后登录信息
     */
    @Transactional
    public void updateLastLogin(String accessKey, String ipAddress) {
        userRepository.findByAccessKey(accessKey).ifPresent(user -> {
            user.setLastLoginTime(new Date());
            user.setLastLoginIp(ipAddress);
            userRepository.save(user);
        });
    }
    
    /**
     * 生成AccessKey
     */
    private String generateAccessKey() {
        return "AK" + UUID.randomUUID().toString().replace("-", "").toUpperCase();
    }
    
    /**
     * 生成SecretKey
     */
    private String generateSecretKey() {
        return UUID.randomUUID().toString().replace("-", "") + 
               UUID.randomUUID().toString().replace("-", "");
    }
    
    /**
     * 重置用户的SK
     */
    @Transactional
    public String resetSecretKey(Long userId) {
        User user = userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("User not found"));
        String newSecretKey = generateSecretKey();
        user.setSecretKey(passwordEncoder.encode(newSecretKey));
        user.setUpdatedAt(new Date());
        userRepository.save(user);
        return newSecretKey;
    }
}

